#include "Camera.h"

namespace M7engine
{
Camera::Camera()
{
	id = -1;
	setPosition(0, 0);
	active = false;
}

Camera::~Camera()
{
	al_destroy_bitmap(buffer);
}

bool Camera::init(int width, int height)
{
	buffer = al_create_bitmap(width, height);

	if (!buffer)
	{
		return false;
	}

	active = true;
	return true;
}

void Camera::draw(ALLEGRO_DISPLAY *display)
{
	al_set_target_backbuffer(display);

	ALLEGRO_TRANSFORM transform;
	float w, h;

    w = al_get_display_width(display);
    h = al_get_display_height(display);

    //al_build_transform(&transform, scrollX - w/2, scrollY - h/2, 1.0, 1.0, 0.0);

	al_identity_transform(&transform);
	al_translate_transform(&transform, -getX(), -getY());
	al_translate_transform(&transform, w * 0.5, h * 0.5);
    al_use_transform(&transform);

    al_draw_bitmap(buffer,0,0,0);

    al_identity_transform(&transform);
    al_use_transform(&transform);
}

CameraManager::CameraManager()
{
}

CameraManager::~CameraManager()
{
}

bool CameraManager::init()
{
	return true;
}

void CameraManager::drawCameras(ALLEGRO_DISPLAY *display)
{
    std::list<Camera*>::iterator iter;
    Camera *camera;
    iter = cameras.begin();

    while (iter != cameras.end())
    {
        camera = *iter;
        if (camera->getActive())
        {
            camera->draw(display);
        }
        iter++;
    }
}

void CameraManager::cleanCameras()
{
    std::list<Camera*>::iterator iter;
    Camera *camera;
    iter = cameras.begin();

    while (iter != cameras.end())
    {
        camera = *iter;
        if (!camera->getActive())
        {
            cameras.erase(iter);
        }
        else
        {
            iter++;
        }
    }
}

void CameraManager::addCamera(Camera *camera)
{
    static int id = 0;
    camera->setID(id);
    cameras.push_back(camera);
    id++;
}

Camera* CameraManager::findCamera(int id)
{
    std::list<Camera*>::iterator iter;
    Camera *camera;
    while (iter != cameras.end())
    {
        camera = *iter;
        if (camera->getID() == id)
        {
            return camera;
        }
        else
        {
            iter++;
        }
    }

    return NULL;
}
}
